﻿namespace RL
{
    using System;
    using System.ComponentModel;
    using System.Globalization;

    public class CurrencyConverter : StringConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (object.ReferenceEquals(sourceType, typeof(string)) || base.CanConvertFrom(context, sourceType));
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                double num;
                string s = value.ToString();
                if (!char.IsNumber(s, 0))
                {
                    s = s.Remove(0, 1);
                }
                if (double.TryParse(s, NumberStyles.Currency, (IFormatProvider) NumberFormatInfo.InvariantInfo, out num))
                {
                    return num;
                }
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (object.ReferenceEquals(destinationType, typeof(string)) & (value is double))
            {
                double num = (double) value;
                return num.ToString("C");
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}

